import React, {useEffect, useState} from 'react';
import axios from "axios";
import {Button, notification, Table} from "antd";
import {CheckOutlined, CloseOutlined} from "@ant-design/icons";

export default function Audit() {
    const [dataSource, setDataSource] = useState([]);

    const {roleId, username, region} = JSON.parse(localStorage.getItem('token'))

    useEffect(() => {
        axios.get(`/news?auditState=1&roleId_jte=${roleId}&publishState_lte=1&_expand=category&_expand=role`).then(res => {
            console.log(res.data)
            // setDataSource(res.data)
            if (roleId === 2) {
                const newdata = [
                    ...res.data.filter(item => item.author === username),
                    // 同区域的下属
                    ...res.data.filter(item => item.region === region && item.roleId === 3)
                ]
                // console.log(newdata)
                setDataSource(newdata)
            } else {
                setDataSource(res.data)
            }
        })
    }, [roleId, username, region])

    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render: (title, item) => {
                return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
            }
            // todo=>限制该列宽
        },
        {
            title: '作者',
            dataIndex: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render: (category) => {
                return category.title
            }
        },
        {
            title: '操作',
            render: (item) => {
                return <div className='noselect'>
                    <Button type="primary" shape="circle" icon={<CheckOutlined/>} onClick={() => {
                        handleAudit(item, 2, 1)
                    }}/>
                    &nbsp;&nbsp;
                    <Button type="primary" shape="circle" danger icon={<CloseOutlined/>} onClick={() => {
                        handleAudit(item, 3, 0)
                    }}/>
                </div>
            }
        },
    ]

    // 审核执行的函数
    const handleAudit = (item, auditState, publishState) => {
        setDataSource(dataSource.filter(data => data.id !== item.id))
        axios.patch(`news/${item.id}`, {
            auditState,
            publishState
        }).then(() => {
            // 通知成功
            notification.info({
                message: '辛苦您！',
                description:
                    auditState === 2 ? `新闻【${item.title}】—— 已通过` : `新闻【${item.title}】—— 未通过`
            })
        })
    }

    return (
        <div>
            <Table dataSource={dataSource} columns={columns}
                   rowKey={item => item.id}/> {/* 因为返回的数据中没有 key 属性，所以需要自己设置一个 rowKey */}
        </div>
    )
}